<?php

class Core_Backend_Component_Permission_Controller_Role extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $areaid = 0) {
        $this->getHistory()->record();
        $collection = App::getModel('permission/collection_role')
                        ->filterByAreaId($this->getSession()->get('managed_area_id'))
                        ->pagination($pageindex, $pagesize)
                        ->asc('a.code')
                        ->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction() {
        $roles = App::getModel('permission/collection_role')
        			->filterByArea()
        			->load();
        $actions = App::getModel('permission/collection_action')
        			->filterByEnabled()
        			->load();
        return $this->viewResult(array('actions' => $actions, 'roles'=>$roles));
    }

    public function editAction($id) {
    	$result = $this->createAction();
        $model = App::getModel('permission/role')->load($id);
        $result->getRoles()->removeItemById($id);
        return $result->setModel($model);
    }
    
    public function deleteAction(){
        App::getModel('permission/role')->deleteBatch($this->getRequest()->getForm('ids'));
        return $this->redirectResult($this->getHistoryUrl('permission/role/index'));
    }
    
   	public function roleActionsAction($roleid){
   		$actions = App::getModel('permission/role')
   						->load($roleid)
   						->getActions()
   						->load();
   		return $this->jsonResult($actions->toArray());
   	}

    public function savePostAction() {
        $data = $this->getRequest()->getForm('role');
        $model = App::getModel('permission/role');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        try{
        	$model->validate();
        	$model->save();
            $this->getMessager()->addInform($this->__('share.message.success'));
            return $this->redirectResult($this->getHistoryUrl('permission/role/index'));       	
        }catch(Core_Model_Permission_Exception_Role $ex){
          	$this->getMessager()->addError($ex->getMessage());
            return $this->createAction()->setActionName('create')->setModel($model);
        }
    }
}